package com.xuhao.didi.oksocket.btnview.help;

import com.xuhao.didi.oksocket.btnview.inface.Film;
import com.xuhao.didi.oksocket.btnview.utils.ClipPathManager;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Path;
import ohos.agp.utils.Color;

/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class FilmHelper implements Film {
    private final Paint clipPaint = new Paint();
    private final Path clipPath = new Path();
    private final Path rectView = new Path();
    private ClipPathManager clipPathManager = new ClipPathManager();
    private boolean isRequestShapeUpdate = true;
    private Component mView;
    private boolean isClipLayout;

    /**
     * 构造
     */
    public FilmHelper() {
        clipPaint.setAntiAlias(true);
        clipPaint.setColor(Color.BLUE);
        clipPaint.setStyle(Paint.Style.FILL_STYLE);
        clipPaint.setStrokeWidth(1);
    }

    @Override
    public void dispatchDraw(Canvas canvas) {
        if (!canClip()) {
            return;
        }
        if (isRequestShapeUpdate) {
            calculateLayout(canvas.getLocalClipBounds().getWidth(), canvas.getLocalClipBounds().getHeight());
            isRequestShapeUpdate = false;
        }
        canvas.drawPath(clipPath, clipPaint);
    }

    @Override
    public void onLayout(int left, int top, int right, int bottom) {
        if (!canClip()) {
            return;
        }
    }

    private void calculateLayout(int width, int height) {
        rectView.reset();
        rectView.addRect(0f, 0f, 1f * getView().getWidth(), 1f * getView().getHeight(), Path.Direction.CLOCK_WISE);
        if (width > 0 && height > 0) {
            clipPathManager.setupClipLayout(width, height);
            clipPath.reset();
            clipPath.set(clipPathManager.getClipPath());
        }
        getView().invalidate();
    }

    public Component getView() {
        return mView;
    }

    /**
     * 是否满足裁剪条件
     *
     * @return true是，反之
     */
    public boolean canClip() {
        return getView() != null && getView() instanceof ComponentContainer && isClipLayout;
    }
}
